package com.wyh.user.listener;

import com.bite.common.utils.JsonUtil;
import com.bite.common.utils.MailUtil;
import com.rabbitmq.client.Channel;
import com.wyh.user.constant.Constant;
import com.wyh.user.dataobject.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;

@Component
@Slf4j
public class UserListener {
    @Autowired
    MailUtil mailUtil;

    @RabbitListener(queues = Constant.USER_QUEUE)
    public void listenerQueue(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            String body = new String(message.getBody());
            UserInfo userInfo = JsonUtil.toObject(body, UserInfo.class);
            userInfo.setPassword("");
            mailUtil.send(userInfo.getEmail(), "欢迎加入WYH_blog", buildContent(userInfo));

            channel.basicAck(deliveryTag, true);
        }catch (Exception e){
            log.error("UserListener.listenerQueue error: message:{}", new String(message.getBody()), e);
            channel.basicNack(deliveryTag,true,false);
        }
    }

    private String buildContent(UserInfo userInfo) {
        return "尊敬的" + userInfo.getUserName() + "欢迎加入WYH_blog社区";
    }
}
